package com.zzuli.yxy;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * EasyExcel开源框架中Converter接口的convertToExcelData只实现了转换
 * BigDecimal、Bolean、Byte[]、btye[]、Byte、Date、Double、File、Float、
 * InputStream、Integer、Long、Short、URL这些类型，
 * 意味着参数data最多只能是个二维数据，但是本次业务逻辑需要转换List< String >的数据
 * @auther pony
 * @create 2023-03-29 14:46
 */
@Component
public class ListStringConverter implements Converter<List> {
    @Override
    public Class supportJavaTypeKey() {
        return List.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    //从excel中读数据时被EasyExcel调用
    @Override
    public List convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String stringValue = cellData.getStringValue();
        String[] split = stringValue.split(",");
        List<String> enterpriseList = new ArrayList<>();
        for(int i = 0; i < split.length; i++){
            enterpriseList.add(split[i]);
        }
        return enterpriseList;
    }

    //写excel文件时被EasyExcel调用
    @Override
    public CellData convertToExcelData(List list, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        list.forEach(o -> {
            String s = o.toString();
            stringBuilder.append(s+",");
        });
        return new CellData(stringBuilder.toString());
    }
}

